package com.epalmpay.service.withdraw.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.epalmpay.bean.BatchPayAddInDTO;
import com.epalmpay.bean.BatchPayInfoBean;
import com.epalmpay.bean.BatchPayQueryBean;
import com.epalmpay.bean.BatchPayRespBean;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.batchpay.BatchOrderInfoOutDTO;
import com.epalmpay.dto.batchpay.BatchPayInDTO;
import com.epalmpay.dto.batchpay.BatchPayInfoInDTO;
import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.entity.BatchPayInfo;
import com.epalmpay.entity.BatchPayRecords;
import com.epalmpay.entity.Group;
import com.epalmpay.entity.Page;
import com.epalmpay.entity.Userbase;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.BatchPayInfoMapper;
import com.epalmpay.mapper.BatchPayRecordsMapper;
import com.epalmpay.mapper.GroupMapper;
import com.epalmpay.mapper.UserbaseMapper;
import com.epalmpay.payplat.BatchPay;
import com.epalmpay.payplat.BatchPayQuery;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.SingleBatchPay;
import com.epalmpay.payplat.SinglePayQuery;
import com.epalmpay.payplat.result.PayBatchPayResult;
import com.epalmpay.payplat.result.SinglePayPayResult;
import com.epalmpay.service.withdraw.IBatchPayService;
import com.epalmpay.util.FileUploadContorller;
import com.epalmpay.util.PropertyCopyUtil;
import com.epalmpay.util.SysUtils;
import com.epalmpay.util.payplat.UtilFun;

import org.springframework.stereotype.Service;


@Service
public class BatchPayServiceImpl implements IBatchPayService{

	private static Logger logger = LoggerFactory.getLogger(BatchPayServiceImpl.class);


	@Resource
	private GroupMapper groupMapper;
	
	@Resource
	private UserbaseMapper userbaseMapper;
	
	@Resource
	private BatchPayRecordsMapper batchPayRecordsMapper;
	
	@Resource
	private BatchPayInfoMapper batchPayInfoMapper;
	
	@Override
	public List<BatchPayRecords> batchPayList(BatchPayInDTO baInDTO,Page page) {
		Group businessBase=this.groupMapper.selectByPrimaryKey(baInDTO.getGroupId());  
		if(businessBase==null)
			return null;
		
		Map<String,Object> map=new HashMap<String,Object>(); 
		map.put("businessId", baInDTO.getGroupId());
	   String datefrom =baInDTO.getDatefrom();
		if(datefrom!=null){
			map.put("datefrom", datefrom); 
		}
		 String dateto =baInDTO.getDateto();
		if(dateto!=null){
			map.put("dateto", dateto); 
		}
		 String batchNo =baInDTO.getBatchNo();
		if(batchNo!=null){
			map.put("batchNo", batchNo); 
		}
		
		
		
		int sumCount=this.batchPayRecordsMapper.selectByPageCounts(map);
		page.setTotalResult(sumCount);
		if(sumCount<=0){
			return new ArrayList<BatchPayRecords>();
		}
		map.put("limit", page.getShowCount());
		map.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		
	   return this.batchPayRecordsMapper.selectByPage(map);
	  
	}
	
	 
		@Override
		public List<BatchPayInfoBean>  batchPayInfoList(BatchPayInDTO batchPayInDTO ,Page page) {
			Group businessBase=this.groupMapper.selectByPrimaryKey(batchPayInDTO.getGroupId());  
			
			
		   BatchPayRecords batchPayRecords=batchPayRecordsMapper.selectByPrimaryKey(batchPayInDTO.getBatchPayId());
			
		   if(businessBase==null||batchPayRecords==null||businessBase.getId().longValue()!=batchPayRecords.getGroupId().longValue()){
				return null;
			}
		   
			Map<String,Object> map=new HashMap<String,Object>(); 
			map.put("groupId", batchPayInDTO.getGroupId());
			map.put("batchPayId", batchPayRecords.getId());
			
			String merchantOrderNo=batchPayInDTO.getMerchantOrderNo();
			if(merchantOrderNo!=null){
				map.put("merchantOrderNo", merchantOrderNo); 
			}
			String datefrom =batchPayInDTO.getDatefrom();
			if(datefrom!=null){
				map.put("datefrom", datefrom); 
			}
			 String dateto =batchPayInDTO.getDateto();
			if(dateto!=null){
				map.put("dateto", dateto); 
			}
			int sumCount=this.batchPayInfoMapper.selectByPageCounts(map);
			page.setTotalResult(sumCount);
			if(sumCount<=0){
				return new ArrayList<BatchPayInfoBean>();
			}
			map.put("limit", page.getShowCount());
			map.put("start", page.getShowCount()*(page.getCurrentPage()-1));
			
	    	return this.batchPayInfoMapper.selectByPage(map); 
		}
	@Override
	public int doAddBatchPay(BatchPayAddInDTO batchPayIn,HttpServletRequest request) throws Exception {
		 //文件保存目录路径
        String savePath =request.getSession().getServletContext().getRealPath("/") ;
//        //文件保存目录URL
        String filepath  = savePath + "/temp/";
        File  tempFile=new File(filepath);
        if(!tempFile.exists()){
        	tempFile.mkdirs();
        }
        String sourceUrl=batchPayIn.getSourceUrl();
        String batchNo=batchPayIn.getBatchNo();
        Group businessBase=this.groupMapper.selectByPrimaryKey(batchPayIn.getGroupId());  
		if(businessBase==null){
			throw new Exception("渠道号参数错误");
		}
		Userbase member= userbaseMapper.selectByPrimaryKey(batchPayIn.getLoginId());
		
		
		if(member==null||!member.getGroupId().equals(businessBase.getId())){
			throw new Exception("渠道号参数错误");
		}
		
	    long	groupId=businessBase.getId();
	    filepath=filepath+SysUtils.getFileName(sourceUrl);
         FileUploadContorller.saveUrlAs(sourceUrl, filepath);
		
        logger.debug("doAddBatchPay...."+filepath);
		Map<String,Object> result= checkInfo(filepath);
		 logger.debug("doAddBatchPay...."+result);
         BatchPayRecords batchPayRecords=new BatchPayRecords();
         if(!batchNo.trim().equals((String)result.get("batchNo"))){
        	 throw new Exception("填写的批次号和文件中不对应");
         }
         batchPayRecords.setBatchNo(batchNo);
         
         batchPayRecords.setGroupId(groupId);
         batchPayRecords.setSourceFile(sourceUrl);
         batchPayRecords.setContactPhone((String)result.get("contactUserPhone"));
         batchPayRecords.setContactUsername((String)result.get("contactUser"));
         batchPayRecords.setCreateTime(new Date());
         batchPayRecords.setCreater(member.getUsername());
         batchPayRecords.setExtendMerchant((String)result.get("extentMerchant"));
         batchPayRecords.setExtendMerchantNo((String)result.get("extentMerchantNo"));
         batchPayRecords.setMerchantInfo((String)result.get("merchantInfo"));
         batchPayRecords.setVersionCode((String)result.get("version"));
         batchPayRecords.setStatus(CommonEnum.BatchRecordStatus.unsubmit.getType());
         batchPayRecords.setTotalAmount(SysUtils.Object2Long(result.get("totalAmount")));
         batchPayRecords.setCountNum(SysUtils.Object2Long(result.get("countNum")));
        int i= batchPayRecordsMapper.insert(batchPayRecords);
        if(i>=0){
        	List<BatchPayInfo> batchPayInfos=( List<BatchPayInfo>)result.get("batchPayInfos");
       		for(BatchPayInfo batchPayInfo :batchPayInfos){
       			batchPayInfo.setBatchPayId(batchPayRecords.getId());
       			batchPayInfo.setGroupId(groupId);
       			batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.unsubmit.getType());
       			batchPayInfo.setGmtCreate(new Date());
       			batchPayInfo.setGmtModified(new Date());
       			batchPayInfo.setHasRepay(0);
       			batchPayInfoMapper.insert(batchPayInfo);
       		}
        }
         
		 return i;
	}
	
	/**
	 * 检验文档的内容 是否正确
	 * @param savePath
	 * @param sourceFile
	 * @return
	 */
	private Map<String, Object> checkInfo(String sourceFile) throws Exception{
		
		String ext =SysUtils.getExt(sourceFile);
        if (ext!=null && !ext.equals("")) {
            if (ext.equals("xls")) {
                return readXlsCheckInfo(sourceFile);
            } else if (ext.equals("xlsx")) {
                return readXlsxCheckInfo(sourceFile);
            }
        }
        throw new Exception("文件格式不正确");
	}
	
	
	/**
     * 读取后缀为xls的excel文件的数据
     * @param path
     * @return List<StudentBean>
     * @author zhang 2015-08-18 00:10
	 * @throws Exception 
     */
    private Map<String, Object> readXlsCheckInfo(String path) throws Exception {
    	Map<String, Object>  result=new HashMap<String, Object>();
        HSSFWorkbook hssfWorkbook = null;
        try {
            InputStream is = new FileInputStream(path);
            hssfWorkbook = new HSSFWorkbook(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new Exception("文件格式错误");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("文件格式错误");
        }
        if (hssfWorkbook != null) {
            // Read the Sheet
               HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
                if (hssfSheet == null) {
                   throw new Exception("文件格式错误");
                }
                //前面的格式验证
                HSSFRow hssfRow = hssfSheet.getRow(0);
                if(hssfRow==null||!"代付明细表".equals(getValue( hssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }
                
                hssfRow = hssfSheet.getRow(1);
                if(hssfRow==null||!"版本号".equals(getValue( hssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }else{
                	String version=getValue( hssfRow.getCell(1)).trim();
                	result.put("version", version);
                }
                
                hssfRow = hssfSheet.getRow(2);
                if(hssfRow==null||!"商户信息".equals(getValue( hssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }else{
                	
                	result.put("merchantInfo", "--");
                }
                
                hssfRow = hssfSheet.getRow(3);
                if(hssfRow==null||!"商户名称".equals(getValue( hssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }else{
                	String extentMerchant=getValue( hssfRow.getCell(1)).trim();
                	result.put("extentMerchant", extentMerchant);
                	
                	String extentMerchantNo=getValue( hssfRow.getCell(5)).trim();
                	result.put("extentMerchantNo", extentMerchantNo);
                }
                
                hssfRow = hssfSheet.getRow(4);
                if(hssfRow==null||!"联系人".equals(getValue( hssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }else{
                	String contactUser=getValue( hssfRow.getCell(1)).trim();
                	result.put("contactUser", contactUser);
                	
                	String contactUserPhone=getValue( hssfRow.getCell(5)).trim();
                	result.put("contactUserPhone", contactUserPhone);
                }
                hssfRow = hssfSheet.getRow(5);
                if(hssfRow==null||!"批次号".equals(getValue( hssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }else{
                	System.out.println("batchNo...."+hssfRow.getCell(1).getCellType());
                	String batchNo=getValue( hssfRow.getCell(1)).trim();
                	result.put("batchNo", batchNo);
          
                }
                hssfRow = hssfSheet.getRow(6);
                if(hssfRow==null||!"订单信息".equals(getValue( hssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }
                hssfRow = hssfSheet.getRow(7);
                if(hssfRow==null||!"商户订单号".equals(getValue( hssfRow.getCell(0)).trim())
                		||!"收款人名称".equals(getValue( hssfRow.getCell(1)).trim())
                		||!"收款人账户".equals(getValue( hssfRow.getCell(2)).trim())
                		||!"收款账户类型".equals(getValue( hssfRow.getCell(3)).trim())
                		||!"交易金额".equals(getValue( hssfRow.getCell(4)).trim())
                		||!"开户行行号".equals(getValue( hssfRow.getCell(5)).trim())
                		||!"开户行名称".equals(getValue( hssfRow.getCell(6)).trim())
                		||!"用途".equals(getValue( hssfRow.getCell(7)).trim())
                		||!"备注".equals(getValue( hssfRow.getCell(8)).trim())){
                	 throw new Exception("文件格式错误");
                }
                //
                List<BatchPayInfo> list = new ArrayList<BatchPayInfo>();
                // Read the Row
                int totalAmount=0;
                int countNum=0;
                for (int rowNum = 8; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                	hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                    	BatchPayInfo batchPayInfo = new BatchPayInfo();
                       
                        batchPayInfo.setMerchantOrderno(getValue( hssfRow.getCell(0)));
                        batchPayInfo.setReceiveUsername(getValue( hssfRow.getCell(1)));
                        batchPayInfo.setReceiveCardno(getValue( hssfRow.getCell(2)));
                        batchPayInfo.setAccountType(getValue( hssfRow.getCell(3)));
                        String amount= getValue( hssfRow.getCell(4));
                        batchPayInfo.setPayAmount((int)Math.round(Double.parseDouble(amount)*100));
                        batchPayInfo.setReceiveBankno(getValue( hssfRow.getCell(5)));
                        batchPayInfo.setReceiveBankname(getValue( hssfRow.getCell(6)));
                        batchPayInfo.setRemark1(getValue( hssfRow.getCell(7)));
                        batchPayInfo.setRemark2(getValue( hssfRow.getCell(8)));
                        list.add(batchPayInfo);
                        totalAmount=totalAmount+batchPayInfo.getPayAmount();
                        countNum=countNum+1;
                    }
                }
                result.put("totalAmount", totalAmount);
                result.put("countNum", countNum);
                result.put("batchPayInfos", list);
            }
        
        return result;
    }

    /**
     * 读取后缀为xlsx的excel文件的数据
     * @param path
     * @return List<StudentBean>
     * @author zhang 2015-08-18 00:08
     * @throws Exception 
     */
    private Map<String, Object> readXlsxCheckInfo(String path) throws Exception{
    	Map<String, Object>  result=new HashMap<String, Object>();
        XSSFWorkbook xssfWorkbook = null;
        try {
            InputStream is = new FileInputStream(path);
            xssfWorkbook = new XSSFWorkbook(is);
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("文件格式错误");
        }
       
       
        if(xssfWorkbook!=null){
            // Read the Sheet
                XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
                if (xssfSheet == null) {
                	throw new Exception("文件格式错误");
                }
                //前面的格式
                XSSFRow xssfRow = xssfSheet.getRow(0);
                if(xssfRow==null||!"代付明细表".equals(getValue( xssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }
                
                xssfRow = xssfSheet.getRow(1);
                if(xssfRow==null||!"版本号".equals(getValue( xssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }else{
                	String version=getValue( xssfRow.getCell(1)).trim();
                	result.put("version", version);
                }
                
                xssfRow = xssfSheet.getRow(2);
                if(xssfRow==null||!"商户信息".equals(getValue( xssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }else{
                	
                	result.put("merchantInfo", "--");
                }
                
                xssfRow = xssfSheet.getRow(3);
                if(xssfRow==null||!"商户名称".equals(getValue( xssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }else{
                	String extentMerchant=getValue( xssfRow.getCell(1)).trim();
                	result.put("extentMerchant", extentMerchant);
                	
                	String extentMerchantNo=getValue( xssfRow.getCell(5)).trim();
                	result.put("extentMerchantNo", extentMerchantNo);
                }
                
                xssfRow = xssfSheet.getRow(4);
                if(xssfRow==null||!"联系人".equals(getValue( xssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }else{
                	String contactUser=getValue( xssfRow.getCell(1)).trim();
                	result.put("contactUser", contactUser);
                	
                	String contactUserPhone=getValue( xssfRow.getCell(5)).trim();
                	result.put("contactUserPhone", contactUserPhone);
                }
                xssfRow = xssfSheet.getRow(5);
                if(xssfRow==null||!"批次号".equals(getValue( xssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }else{
                	System.out.println("batchNo...."+xssfRow.getCell(1).getCellType());
                	String batchNo=getValue( xssfRow.getCell(1)).trim();
                	result.put("batchNo", batchNo);
                	
          
                }
                xssfRow = xssfSheet.getRow(6);
                if(xssfRow==null||!"订单信息".equals(getValue( xssfRow.getCell(0)).trim())){
                	 throw new Exception("文件格式错误");
                }
                xssfRow = xssfSheet.getRow(7);
                if(xssfRow==null||!"商户订单号".equals(getValue( xssfRow.getCell(0)).trim())
                		||!"收款人名称".equals(getValue( xssfRow.getCell(1)).trim())
                		||!"收款人账户".equals(getValue( xssfRow.getCell(2)).trim())
                		||!"收款账户类型".equals(getValue( xssfRow.getCell(3)).trim())
                		||!"交易金额".equals(getValue( xssfRow.getCell(4)).trim())
                		||!"开户行行号".equals(getValue( xssfRow.getCell(5)).trim())
                		||!"开户行名称".equals(getValue( xssfRow.getCell(6)).trim())
                		||!"用途".equals(getValue( xssfRow.getCell(7)).trim())
                		||!"备注".equals(getValue( xssfRow.getCell(8)).trim())){
                	 throw new Exception("文件格式错误");
                }
                //
                List<BatchPayInfo> list = new ArrayList<BatchPayInfo>();
             // Read the Row
                int totalAmount=0;
                int countNum=0;
                for (int rowNum = 8; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                	xssfRow = xssfSheet.getRow(rowNum);
                    if (xssfRow != null) {
                    	BatchPayInfo batchPayInfo = new BatchPayInfo();
                       
                        batchPayInfo.setMerchantOrderno(getValue( xssfRow.getCell(0)));
                        batchPayInfo.setReceiveUsername(getValue( xssfRow.getCell(1)));
                        batchPayInfo.setReceiveCardno(getValue( xssfRow.getCell(2)));
                        batchPayInfo.setAccountType(getValue( xssfRow.getCell(3)));
                        String amount= getValue( xssfRow.getCell(4));
                        batchPayInfo.setPayAmount((int)Math.round(Double.parseDouble(amount)*100));
                        batchPayInfo.setReceiveBankno(getValue( xssfRow.getCell(5)));
                        batchPayInfo.setReceiveBankname(getValue( xssfRow.getCell(6)));
                        batchPayInfo.setRemark1(getValue( xssfRow.getCell(7)));
                        batchPayInfo.setRemark2(getValue( xssfRow.getCell(8)));
                        list.add(batchPayInfo);
                        totalAmount=totalAmount+batchPayInfo.getPayAmount();
                        countNum=countNum+1;
                    }
                }
                result.put("totalAmount", totalAmount);
                result.put("countNum", countNum);
                result.put("batchPayInfos", list);
            }
        return result;
    }

    /**
     * 判断后缀为xlsx的excel文件的数据类型
     * @param xssfRow
     * @return String
     * @author zhang 2015-08-18 00:12
     */
  
    private String getValue(XSSFCell xssfRow) {
        if (xssfRow.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(xssfRow.getBooleanCellValue());
        } else if (xssfRow.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {

            String result= String.valueOf(xssfRow.getNumericCellValue());
            String regex="^((\\d+.?\\d+)[Ee]{1}(\\d+))$";
            Pattern pattern = Pattern.compile(regex);
            Matcher m = pattern.matcher(result);
            if(m.matches()){
            	DecimalFormat df = new DecimalFormat("#.##");
                return  df.format(Double.parseDouble(result));
            }else{
            	return result;
            }
        } else {
            return String.valueOf(xssfRow.getStringCellValue());
        }
    }

    /**
     * 判断后缀为xls的excel文件的数据类型
     * @param hssfCell
     * @return String
     * @author zhang 2015-08-18 00:12
     */
 
    private String getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
        	
            String result= String.valueOf(hssfCell.getNumericCellValue());
            String regex="^((\\d+.?\\d+)[Ee]{1}(\\d+))$";
            Pattern pattern = Pattern.compile(regex);
            Matcher m = pattern.matcher(result);
            if(m.matches()){
            	DecimalFormat df = new DecimalFormat("#.##");
                return  df.format(Double.parseDouble(result));
            }else{
            	return result;
            }
        } else {
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }
	@Override
	public BatchOrderInfoOutDTO findBatchOrderInfo(Long orderId) throws Exception {
		// TODO Auto-generated method stub
		 
		 BatchPayRecords  batchPayRecords=batchPayRecordsMapper.selectByPrimaryKey(orderId);
		 BatchOrderInfoOutDTO result=new BatchOrderInfoOutDTO();
		 PropertyCopyUtil.copyProperties(batchPayRecords, result);
		 //查找成功的金额，笔数
		 Map<String,Object> resultSuccess=batchPayInfoMapper.selectInfoByStatus(1,orderId);
		 result.setSuccessAmount(SysUtils.Object2Long(resultSuccess.get("amount")));
		 result.setSuccessCountNum(SysUtils.Object2int(resultSuccess.get("countNum")));
		 //查找失败的金额，笔数
		 Map<String,Object> resultFail=batchPayInfoMapper.selectInfoByStatus(-1,orderId);
		 result.setErrorAmount(SysUtils.Object2Long(resultFail.get("amount")));
		 result.setErrorCountNum(SysUtils.Object2int(resultFail.get("countNum")));
		 //查找进行中的金额笔数
		 Map<String,Object> resultInProcess=batchPayInfoMapper.selectInfoByStatus(0,orderId);
		 result.setInProcessAmount(SysUtils.Object2Long(resultInProcess.get("amount")));
		 result.setInProcessCountNum(SysUtils.Object2int(resultInProcess.get("countNum")));
		 return result;
	}
	
	
	@Override
	public BaseOutDTO finishBatchPay(BatchPayInDTO batchPayIn) throws ApplicationException{
		
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		BatchPayRecords batchPayRecords=batchPayRecordsMapper.selectByPrimaryKey(batchPayIn.getBatchPayId());
		if(batchPayRecords.getStatus().intValue()==-1||batchPayRecords.getStatus().intValue()==0){
			//
			Group businessBase=groupMapper.selectByPrimaryKey(batchPayRecords.getGroupId());
			String versionCode=batchPayRecords.getVersionCode();
			String mchtBatchNo=batchPayRecords.getBatchNo();
			List<BatchPayInfo>batchPayInfos=batchPayInfoMapper.selectByBatchId(batchPayRecords.getId(),batchPayRecords.getGroupId());
			List<Map<String,Object>>infos=new ArrayList<Map<String,Object>>();
			for(BatchPayInfo payInfo:batchPayInfos){
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("merchantOrderno", payInfo.getMerchantOrderno().trim());
				map.put("receiveUsername", payInfo.getReceiveUsername().trim());
				map.put("receiveCardno", payInfo.getReceiveCardno().trim());
				map.put("payAmount", payInfo.getPayAmount());
				map.put("receiveBankname", payInfo.getReceiveBankname().trim());
				map.put("receiveBankno", payInfo.getReceiveBankno().trim());
				map.put("accountType", payInfo.getAccountType().trim());
				
				map.put("remark1", payInfo.getRemark1().trim());
				map.put("remark2", payInfo.getRemark2().trim());
				infos.add(map);
			}
			
			String payInfos=JSONObject.toJSONString(infos);
			BatchPay batchPay=BatchPay.initialize(businessBase.getPayGroupCode(), versionCode, mchtBatchNo, payInfos);
			PayBatchPayResult result=IPayAPI.finishBatchPay(batchPay);
			if(result.getRespCode().equals("0000")){
				batchPayRecords.setStatus(CommonEnum.BatchRecordStatus.inProcess.getType());
				batchPayRecords.setRespondInfo(result.getRespCode()+":"+result.getMsgTxt());
				batchPayRecordsMapper.updateByPrimaryKey(batchPayRecords);
				/**
				 * 处理单笔记录
				 */
				/**
				 * 处理单笔记录
				 */
				List<BatchPayRespBean> payinfos=UtilFun.getJavaBeanCollection(BatchPayRespBean.class, result.getResult());
				if(payinfos!=null){
					for(BatchPayRespBean paybean:payinfos){
						BatchPayInfo batchPayInfo=batchPayInfoMapper.findBatchInfoByOrderAndBatchId(paybean.getMchtOrderNo(),batchPayRecords.getId());
						
						if("E0000".equals(paybean.getResponseCode())){
							batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.inProcess.getType());
							batchPayInfo.setRespondInfo(paybean.getResponseMsg());
						}else{
							batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.submit_fail.getType());
							batchPayInfo.setRespondInfo(paybean.getResponseMsg());						
						}						
		       			batchPayInfo.setGmtModified(new Date());
						batchPayInfoMapper.updateByPrimaryKey(batchPayInfo);
					}
				}
				baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
			}else{
				batchPayRecords.setStatus(CommonEnum.BatchRecordStatus.submit_fail.getType());
				batchPayRecords.setRespondInfo(result.getRespCode()+":"+result.getMsgTxt());
				batchPayRecordsMapper.updateByPrimaryKey(batchPayRecords);
				baseOutDTO.setErrorCode(result.getRespCode(), result.getMsgTxt());
				
			}
		}
		return baseOutDTO;
	}
	@Override
	public int finishSinglePay (BatchPayInfoInDTO batchPayInfoIn) throws ApplicationException {
		BatchPayInfo batchPayInfo=batchPayInfoMapper.selectByPrimaryKey(batchPayInfoIn.getId());
		
		BatchPayRecords batchPayRecords=batchPayRecordsMapper.selectByPrimaryKey(batchPayInfo.getBatchPayId());
		
		if(batchPayRecords.getStatus().intValue()>CommonEnum.BatchRecordStatus.unsubmit.getType()){
			//进行单笔提交
			if(batchPayInfo.getStatus().intValue()==CommonEnum.BatchRecordStatus.fail.getType()
				||batchPayInfo.getStatus().intValue()==CommonEnum.BatchRecordStatus.submit_fail.getType()){
				Group businessBase=groupMapper.selectByPrimaryKey(batchPayRecords.getGroupId());
				//插入一条补代付订单
				 
				BatchPayInfo tbatchPayInfo=new BatchPayInfo();
				tbatchPayInfo.setReceiveBankname(batchPayInfoIn.getReceiveBankname());
				
				tbatchPayInfo.setAccountType(batchPayInfoIn.getAccountType());
				tbatchPayInfo.setReceiveBankno(batchPayInfoIn.getReceiveBankno());
				tbatchPayInfo.setReceiveCardno(batchPayInfoIn.getReceiveCardno());
				
				tbatchPayInfo.setReceiveUsername(batchPayInfoIn.getReceiveUsername());
				
				tbatchPayInfo.setRemark1(batchPayInfoIn.getRemark1());
				
				if(StringUtils.isNotBlank(batchPayInfoIn.getRemark2())){
					tbatchPayInfo.setRemark2(batchPayInfoIn.getRemark2());
				}			
				tbatchPayInfo.setPayAmount(batchPayInfo.getPayAmount());
				tbatchPayInfo.setRelatePayInfoId(batchPayInfo.getId());
				tbatchPayInfo.setGroupId(batchPayInfo.getGroupId());
				tbatchPayInfo.setBatchPayId(batchPayInfo.getBatchPayId());
				tbatchPayInfo.setMerchantOrderno(reloadMerchantOrderno(batchPayInfo.getId()));
				
				
				String accountType=tbatchPayInfo.getAccountType() ;
				String mchtOrderNo=tbatchPayInfo.getMerchantOrderno()  ;
				String accountNo =tbatchPayInfo.getReceiveCardno();
				String accountName=tbatchPayInfo.getReceiveUsername();
				String  bankName=tbatchPayInfo.getReceiveBankname();
				String amt=tbatchPayInfo.getPayAmount()+"";
				String bankNo=tbatchPayInfo.getReceiveBankno();
				String remark=tbatchPayInfo.getRemark1()+"-"+tbatchPayInfo.getRemark2();
				SingleBatchPay batchPay=SingleBatchPay.initialize(businessBase.getPayGroupCode(), accountType, mchtOrderNo, accountNo, accountName, bankName, amt, bankNo, remark);
				SinglePayPayResult result=IPayAPI.finishSinglePay(batchPay);
				if(result.getRespCode().equals("0000")){
					if("TX_BEGIN".equals(result.getStatus())){
						batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.reInProcess .getType());
						batchPayInfo.setRespondInfo(result.getMsgTxt());
						batchPayInfo.setGmtModified(new Date());
						batchPayInfo.setHasRepay(1);
						batchPayInfoMapper.updateByPrimaryKey(batchPayInfo);	
						tbatchPayInfo.setGmtCreate(new Date());
						tbatchPayInfo.setGmtModified(new Date());
						tbatchPayInfo.setHasRepay(0);
						tbatchPayInfo.setStatus(CommonEnum.BatchRecordStatus.inProcess.getType());
						tbatchPayInfo.setRespondInfo("交易处理中");
						batchPayInfoMapper.insert(tbatchPayInfo);
					}
					
				}else{
					throw new ApplicationException(result.getRespCode()+":"+result.getMsgTxt());
				}
			}else{
				throw new ApplicationException("当前记录不能进行此操作");
			}
			
		}else{
			throw new ApplicationException("请先完成批量提交");
		}
		return 0;
	}


	private String reloadMerchantOrderno(Long recordId ) {
		
		return "BC"+SysUtils.formatDate("MMddHHmm")+SysUtils.formatString(recordId, 9);
	}


	@Override
	public BatchPayRecords findBatchPayRecord(Long batchPayId) {
		
		return batchPayRecordsMapper.selectByPrimaryKey(batchPayId);
	}


	@Override
	public BaseOutDTO finishsynBatchRecord(BatchPayInDTO batchPayIn) {
		
		BaseOutDTO baseOutDTO =new BaseOutDTO();
		BatchPayRecords batchPayRecords=batchPayRecordsMapper.selectByPrimaryKey(batchPayIn.getBatchPayId());
	
	  if(batchPayRecords.getStatus().intValue()==CommonEnum.BatchRecordStatus.inProcess.getType()
			  ||batchPayRecords.getStatus().intValue()==CommonEnum.BatchRecordStatus.subSuccecess.getType()){
		  Group businessBase=groupMapper.selectByPrimaryKey(batchPayRecords.getGroupId());			
		  //完成查询 结果
		  BatchPayQuery batchPayQuery=BatchPayQuery.initialize(businessBase.getPayGroupCode(), batchPayRecords.getBatchNo());
		  PayBatchPayResult payBatchPayResult= IPayAPI.finishBatchPayQuery(batchPayQuery);
			if(payBatchPayResult.getRespCode().equals("0000")){
				/**
				 * 处理单笔记录
				 */
				List<BatchPayQueryBean> payinfos=UtilFun.getJavaBeanCollection(BatchPayQueryBean.class, payBatchPayResult.getResult());
				if(payinfos!=null){
					for(BatchPayQueryBean paybean:payinfos){
						BatchPayInfo batchPayInfo=batchPayInfoMapper.findBatchInfoByOrderAndBatchId(paybean.getMchtOrderNo(),batchPayRecords.getId());
						//表示 进行补充代付的记录，查询结果不发生改变
						if(batchPayInfo!=null&&batchPayInfo.getRelatePayInfoId()==null){
							if("交易成功".equals(paybean.getStatus())){
								batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.Succecess.getType());
								batchPayInfo.setRespondInfo(paybean.getStatus());
							}else if("已受理".equals(paybean.getStatus())||"交易中".equals(paybean.getStatus())){
								batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.inProcess.getType());
								batchPayInfo.setRespondInfo(paybean.getStatus());
							}else{
								batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.fail.getType());
								batchPayInfo.setRespondInfo(paybean.getStatus());
							}
							batchPayInfo.setGmtModified(new Date());
							batchPayInfoMapper.updateByPrimaryKey(batchPayInfo);
						}
					}
				}				
				 this.checkBatchPayStatus(batchPayRecords);
				 
				 baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
			}else{
				 baseOutDTO.setErrorCode(payBatchPayResult.getRespCode()+":"+payBatchPayResult.getMsgTxt());
			}
		 
	  }else{
		  baseOutDTO.setErrorCode(Rescode.FAIL, "批量代付订单未提交成功");
	  }
	  return baseOutDTO;
	}

	/**
	 * 检查代付状态
	 */
	private  void checkBatchPayStatus(BatchPayRecords batchPayRecords){
		//如果不是全部成功 就检查订单
		if(batchPayRecords.getStatus().intValue()==CommonEnum.BatchRecordStatus.inProcess.getType()
				||batchPayRecords.getStatus().intValue()==CommonEnum.BatchRecordStatus.subSuccecess.getType()){
			List<BatchPayInfo> batchPayInfos=batchPayInfoMapper.selectByBatchId(batchPayRecords.getId(), batchPayRecords.getGroupId());
		    boolean allSuccess=true;
			for(BatchPayInfo batchPayInfo :batchPayInfos){
		    	if(batchPayInfo.getStatus().intValue()!=CommonEnum.BatchRecordStatus.Succecess.getType()
		    			&&batchPayInfo.getStatus().intValue()!=CommonEnum.BatchRecordStatus.add_success.getType()){	    		
		    		allSuccess=false;
		    		break;
		    	} 	
		    }
			if(allSuccess){
				batchPayRecords.setStatus(CommonEnum.BatchRecordStatus.Succecess.getType());
	    	}else{
	    		batchPayRecords.setStatus(CommonEnum.BatchRecordStatus.subSuccecess.getType());
	    	}
			batchPayRecordsMapper.updateByPrimaryKey(batchPayRecords);
		}
	}

	@Override
	public BaseOutDTO finishUpdatePayInfo(BatchPayInfoInDTO batchPayInfoIn) {
		BaseOutDTO baseOutDTO =new BaseOutDTO();
		BatchPayInfo batchPayInfo=batchPayInfoMapper.selectByPrimaryKey(batchPayInfoIn.getId());
		if(batchPayInfo!=null){
			
			if(StringUtils.isNotBlank(batchPayInfoIn.getReceiveBankname())){
				batchPayInfo.setReceiveBankname(batchPayInfoIn.getReceiveBankname());
			}
			
			if(StringUtils.isNotBlank(batchPayInfoIn.getAccountType())){
				batchPayInfo.setAccountType(batchPayInfoIn.getAccountType());
			}
			if(StringUtils.isNotBlank(batchPayInfoIn.getReceiveBankno())){
				batchPayInfo.setReceiveBankno(batchPayInfoIn.getReceiveBankno());
			}
			if(StringUtils.isNotBlank(batchPayInfoIn.getReceiveCardno())){
				batchPayInfo.setReceiveCardno(batchPayInfoIn.getReceiveCardno());
			}
			
			if(StringUtils.isNotBlank(batchPayInfoIn.getReceiveUsername())){
				batchPayInfo.setReceiveUsername(batchPayInfoIn.getReceiveUsername());
			}
			
			if(StringUtils.isNotBlank(batchPayInfoIn.getRemark1())){
				batchPayInfo.setRemark1(batchPayInfoIn.getRemark1());
			}
			

			if(StringUtils.isNotBlank(batchPayInfoIn.getRemark2())){
				batchPayInfo.setRemark2(batchPayInfoIn.getRemark2());
			}
			batchPayInfo.setGmtModified(new Date());
			batchPayInfoMapper.updateByPrimaryKey(batchPayInfo);
			baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
			
		}else{
			  baseOutDTO.setErrorCode(Rescode.FAIL, "记录未查询到");
		  }
		  return baseOutDTO;
	}


	@Override
	public BatchPayInfo findSinglePayInfo(Long batchPayInfoId) {
		
		return batchPayInfoMapper.selectByPrimaryKey(batchPayInfoId);
	}


	@Override
	public BaseOutDTO finishSycPayResult(Long batchPayInfoId) {
		BaseOutDTO baseOutDTO =new BaseOutDTO();
		BatchPayInfo batchPayInfo=batchPayInfoMapper.selectByPrimaryKey(batchPayInfoId);
		
		
		if(batchPayInfo!=null){
			BatchPayRecords batchPayRecords=batchPayRecordsMapper.selectByPrimaryKey(batchPayInfo.getBatchPayId());
			if(batchPayInfo.getRelatePayInfoId()!=null){
				//如果当前这笔交易记录为单笔代付记录查询
				Group businessBase=groupMapper.selectByPrimaryKey(batchPayInfo.getGroupId());							 
				SinglePayQuery singlePayQuery=SinglePayQuery.initialize(businessBase.getPayGroupCode(), batchPayInfo.getMerchantOrderno());
				SinglePayPayResult result=IPayAPI.finishSinglePayQuery(singlePayQuery);
				if(result.getRespCode().equals("0000")){
					String status=result.getStatus();
					if("INVALID".equals(status)||"TX_FAIL".equals(status)||"CLOSED".equals(status)){
						//交易失败
						batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.fail.getType());
						batchPayInfo.setRespondInfo(result.getOrderDesc());
						batchPayInfo.setGmtModified(new Date());
						batchPayInfoMapper.updateByPrimaryKey(batchPayInfo);
						//查询关联的提现记录
						BatchPayInfo upBatchPayInfo=batchPayInfoMapper.selectByPrimaryKey(batchPayInfo.getRelatePayInfoId());
						upBatchPayInfo.setStatus(CommonEnum.BatchRecordStatus.fail.getType());
						upBatchPayInfo.setGmtModified(new Date());
						batchPayInfoMapper.updateByPrimaryKey(upBatchPayInfo);
						//交易处理中
						baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
						return baseOutDTO;
					}
					else if("TX_SUCCESS".equals(status)){
						//交易成功
						batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.Succecess.getType());
						batchPayInfo.setRespondInfo(result.getOrderDesc());
						batchPayInfo.setGmtModified(new Date());
						batchPayInfoMapper.updateByPrimaryKey(batchPayInfo);
						//查询关联的提现记录
						BatchPayInfo upBatchPayInfo=batchPayInfoMapper.selectByPrimaryKey(batchPayInfo.getRelatePayInfoId());
						upBatchPayInfo.setStatus(CommonEnum.BatchRecordStatus.add_success.getType());
						upBatchPayInfo.setGmtModified(new Date());
						batchPayInfoMapper.updateByPrimaryKey(upBatchPayInfo);
						
						
						baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
						this.checkBatchPayStatus(batchPayRecords);
						return baseOutDTO;
					}
					else {
						//交易处理中
						baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
						return baseOutDTO;
					}
				}else{
					  baseOutDTO.setErrorCode(Rescode.FAIL, "查询结果，通道错误"+result.getMsgTxt());
					  return baseOutDTO;
				}
				
			}else{
				//如果当前这笔交易记录不是这笔
				BatchPayInfo batchPayInfo2=batchPayInfoMapper.lastRelatePayInfo(batchPayInfoId);
				if(batchPayInfo2==null){
					 baseOutDTO.setErrorCode(Rescode.FAIL, "记录未查询到");
					 return baseOutDTO;
				}
				Group businessBase=groupMapper.selectByPrimaryKey(batchPayInfo.getGroupId());							 				
				SinglePayQuery singlePayQuery=SinglePayQuery.initialize(businessBase.getPayGroupCode(), batchPayInfo2.getMerchantOrderno());
				SinglePayPayResult result=IPayAPI.finishSinglePayQuery(singlePayQuery);
				if(result.getRespCode().equals("0000")){
					String status=result.getStatus();
					if("INVALID".equals(status)||"TX_FAIL".equals(status)||"CLOSED".equals(status)){
						//交易失败
						batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.fail.getType());
						batchPayInfo.setRespondInfo(result.getOrderDesc());
						batchPayInfo.setGmtModified(new Date());
						batchPayInfoMapper.updateByPrimaryKey(batchPayInfo);
						//查询关联的提现记录
						batchPayInfo2.setStatus(CommonEnum.BatchRecordStatus.fail.getType());
						batchPayInfo2.setGmtModified(new Date());
						batchPayInfoMapper.updateByPrimaryKey(batchPayInfo2);
						//交易处理中
						baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
						return baseOutDTO;
					}
					else if("TX_SUCCESS".equals(status)){
						//交易成功
						batchPayInfo.setStatus(CommonEnum.BatchRecordStatus.add_success.getType());
						batchPayInfo.setGmtModified(new Date());
						batchPayInfoMapper.updateByPrimaryKey(batchPayInfo);
						//查询关联的提现记录
						batchPayInfo2.setStatus(CommonEnum.BatchRecordStatus.Succecess.getType());
						batchPayInfo2.setRespondInfo("账户信息错误");
						batchPayInfo2.setGmtModified(new Date());
						batchPayInfoMapper.updateByPrimaryKey(batchPayInfo2);
						//交易处理中
						this.checkBatchPayStatus(batchPayRecords);
						baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
						return baseOutDTO;
					}
					else {
						//交易处理中
						baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
						return baseOutDTO;
					}
				}else{
					  baseOutDTO.setErrorCode(Rescode.FAIL, "查询结果，通道错误"+result.getMsgTxt());
					  return baseOutDTO;
				}
				
			}
			
			
		}else{
			  baseOutDTO.setErrorCode(Rescode.FAIL, "记录未查询到");
		  }
		  return baseOutDTO;
	}


	@Override
	public List<BatchPayInfoBean> batchRepayList(BatchPayInDTO batchPayIn) {
		return this.batchPayInfoMapper.batchRepayList(batchPayIn.getBatchPayInfoId()); 
	}


	
}
